package com.luck.easyfoodbatch.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.DemoHelper;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.entity.GsonGb;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods2Model;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods2Presenter;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods2View;
import com.luck.easyfoodbatch.mvp.model.Goods2Model;
import com.luck.easyfoodbatch.pickerview.PopBatchHelper;
import com.luck.easyfoodbatch.pickerview.PopBirthHelper;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.BaseViewHolder;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;
import com.luck.easyrecyclerview.swipe.MyLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UploadBatchActivity extends BaseActivity implements PublicGoods2View {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.right_title)
    TextView rightTitle;
    @BindView(R.id.btn_next_batch)
    Button btn_exchange;
    private PublicGoods2Model goods2Model;
    private BatchAdapter adapter;
    private List<GsonGb> list = new ArrayList<>();
    private List<GsonGb.Bean> beanList = new ArrayList<>();
    private Handler handler = new Handler();
    private Gson gson;
    private String gid = "";
    private int product_type = 0;
    public double mail = 0;// 数量
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("app.data.refresh")) {
                //getItemData();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_batch, "上传商品(库存批次)", "添加批次", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        registerReceiver(receiver, "app.data.refresh");
        gson = new Gson();
        mail = getIntent().getDoubleExtra("mail", 0);
        gid = getIntent().getStringExtra("gid");
        product_type = getIntent().getIntExtra("product_type", 0);
        // 批次
        GsonGb gsonGb = new GsonGb();
        gsonGb.setDue_date("");
        gsonGb.setStock("");
        GsonGb.Bean bean = new GsonGb.Bean();
        bean.setPrice("");
        bean.setSold_province("0");
        bean.setName("全国");
        beanList.add(bean);
        gsonGb.setData_json(beanList);
        list.add(gsonGb);// 默认显示一个批次

        adapter = new BatchAdapter(this, list, mail);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0), getResources().getColor(R.color.transparent)));
        recyclerView.setLayoutManager(manager);
        adapter.addAll(list);
        recyclerView.setAdapter(adapter);

    }

    @OnClick({R.id.right_title, R.id.btn_next_batch})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_title:
                // 批次
                System.out.print(list.size());
                GsonGb gsonGb = new GsonGb();
                gsonGb.setStock("");
                gsonGb.setDue_date("");
                List<GsonGb.Bean> been = new ArrayList<>();
                GsonGb.Bean item = new GsonGb.Bean();
                item.setName("全国");
                item.setSold_province("0");
                item.setPrice("");
                been.add(item);
                gsonGb.setData_json(been);
                list.add(gsonGb);

                adapter.clear();
                adapter.addAll(list);
                adapter.notifyDataSetChanged();

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        recyclerView.scrollToPosition(list.size());
                    }
                });
                break;
            case R.id.btn_next_batch:
                String json = gson.toJson(list);
                if (!Tools.isNull(json)) {
                    showProgressDialog("正在加载，请稍候……");
                    goods2Model = new PublicGoods2Presenter(this, mContext);
                    goods2Model.uploadGoods(gid, json);
                } else {
                    T.showToast(mContext, "请输入商品批次");
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void publicGoods2Success(Goods2Model model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("gid", gid);
                bundle.putInt("product_type", product_type);
                intent.setClass(mContext, UploadParameterActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 400);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    public static class BatchAdapter extends RecyclerArrayAdapter<GsonGb> {
        private PopBatchHelper birthHelper;
        private LayoutInflater mInflater;
        public Context mContext;
        private String unit;// 单位
        private List<GsonGb> list;
        private double mail;

        public BatchAdapter(Context context, List<GsonGb> list, double mail) {
            super(context);
            this.mContext = context;
            mInflater = LayoutInflater.from(mContext);
            birthHelper = new PopBatchHelper(context);
            this.list = list;
            this.mail = mail;
        }

        public void setUnit(String unit) {
            this.unit = unit;
        }

        public interface OnItemClickListener {
            void onItemClick(int position, View v);
        }

        public OnItemClickListener mItemClickListener;


        public void setOnItemClickListener(OnItemClickListener listener) {
            this.mItemClickListener = listener;
        }

        @Override
        public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {

            return new ViewHolder(parent);
        }

        public class ViewHolder extends BaseViewHolder<GsonGb> {
            RecyclerView recycler;
            TextView tv_add_batch, tv_remove, tv_time, tv_right_unit;
            EditText et_stock;

            public ViewHolder(ViewGroup parent) {
                super(parent, R.layout.batch_item);

                tv_add_batch = $(R.id.tv_add_batch);
                tv_remove = $(R.id.tv_remove);
                recycler = $(R.id.recycler);
                tv_time = $(R.id.tv_time);
                et_stock = $(R.id.et_stock);
                tv_right_unit = $(R.id.tv_right_unit);
                MyLayoutManager manager = new MyLayoutManager(mContext);
                manager.setOrientation(LinearLayoutManager.VERTICAL);
                recycler.addItemDecoration(new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), mContext.getResources().getColor(R.color.line_color)));
                recycler.setLayoutManager(manager);
            }

            @Override
            public void setData(final GsonGb gsonGb, final int position) {
                tv_remove.setTag(position);
                tv_remove.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int index = (int) view.getTag();
                        if (index == 0) {
                            T.showToast(mContext, "默认第一个批次不能删除~");
                        } else {
                            showDeleteDialog(position, getAdapterPosition());
                        }
                    }
                });
                et_stock.setTag(position);//通过设置tag，防止position紊乱
                tv_time.setTag(position);//通过设置tag，防止position紊乱
                et_stock.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        int index = (int) et_stock.getTag();
                        GsonGb gb = list.get(index);
                        gb.setStock(editable.toString());
                    }
                });
                tv_time.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        int index = (int) tv_time.getTag();
                        GsonGb gb = list.get(index);
                        gb.setDue_date(editable.toString());
                    }
                });
                et_stock.setText(gsonGb.getStock());
                tv_time.setText(gsonGb.getDue_date());
                final List<GsonGb.Bean> data_json = gsonGb.getData_json();
                final BatchItemAdapter adapter = new BatchItemAdapter(position, data_json, list, mail);
                recycler.setAdapter(adapter);
                if (Tools.isNull(unit)) {
                    tv_right_unit.setText("件");
                } else {
                    tv_right_unit.setText(unit);
                }
                tv_add_batch.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 添加售卖地区
                        GsonGb.Bean bean = new GsonGb.Bean();
                        bean.setPrice("");
                        bean.setSold_province("0");
                        bean.setName("全国");
                        data_json.add(bean);
                        gsonGb.setData_json(data_json);
                        adapter.notifyDataSetChanged();
                    }
                });

                //itemView 的点击事件
                if (mItemClickListener != null) {
                    itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mItemClickListener.onItemClick(getAdapterPosition(), v);
                        }
                    });
                }
                tv_time.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 选择时间
                        birthHelper.setOnClickOkListener(new PopBatchHelper.OnClickOkListener() {
                            @Override
                            public void onClickOk(String birthday) {
                                tv_time.setText(birthday);
                            }
                        });
                        birthHelper.show(view);
                    }
                });
            }
        }

        /**
         * 删除批次提示
         */
        private void showDeleteDialog(final int position, final int adapterPosition) {
            final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                    App.screenHeight / 4, R.layout.wind_base_dialog_xml, R.style.Theme_dialog);
            Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
            Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
            TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
            tv_content.setText("确定删除该批次吗？");
            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            btn_commit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    remove(adapterPosition);
                    list.remove(position);
                    notifyItemRemoved(adapterPosition);
                    dialog.dismiss();
                }
            });
            dialog.show();
        }

        /**
         * 批次
         */
        private class BatchItemAdapter extends RecyclerView.Adapter<BatchItemAdapter.ViewHolder> {

            private int index = 0;
            private List<GsonGb.Bean> data_json;
            private List<GsonGb> list;
            private double mail;

            public BatchItemAdapter(int index, List<GsonGb.Bean> data_json, List<GsonGb> list, double mail) {
                super();
                this.index = index;
                this.data_json = data_json;
                this.list = list;
                this.mail = mail;
            }

            @Override
            public BatchItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = mInflater.inflate(R.layout.batch_item_item,
                        parent, false);
                return new ViewHolder(view);
            }

            @Override
            public void onBindViewHolder(final BatchItemAdapter.ViewHolder holder, final int position) {
                if (index == 0 && position == 0) {
                    holder.iv_remove.setVisibility(View.GONE);
                } else {
                    holder.iv_remove.setVisibility(View.VISIBLE);
                }
                final GsonGb.Bean bean = data_json.get(position);
                holder.tv_price.setTag(position); //通过设置tag，防止position紊乱
                holder.tv_city.setTag(position);//通过设置tag，防止position紊乱
                holder.et_unit_price.setTag(position);//通过设置tag，防止position紊乱
                holder.et_unit_price.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        if (!Tools.isNull(editable.toString())) {
                            double unit_price = Double.parseDouble(editable.toString());
                            double singe_price = mail * unit_price;
                            holder.tv_price.setText(singe_price + "");
                        } else {
                            holder.tv_price.setText("");
                        }
                        int itemIndex = (int) holder.et_unit_price.getTag();
                        List<GsonGb.Bean> data_json = list.get(index).getData_json();
                        GsonGb.Bean item = data_json.get(itemIndex);
                        item.setSingle_price(editable.toString());
                    }
                });

                holder.tv_price.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        int itemIndex = (int) holder.tv_price.getTag();
                        List<GsonGb.Bean> data_json = list.get(index).getData_json();
                        GsonGb.Bean item = data_json.get(itemIndex);
                        item.setPrice(editable.toString());
                    }
                });

                holder.tv_city.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        int itemIndex = (int) holder.tv_city.getTag();
                        List<GsonGb.Bean> data_json = list.get(index).getData_json();
                        GsonGb.Bean item = data_json.get(itemIndex);
                        item.setName(editable.toString());
                    }
                });


                holder.tv_price.setText(bean.getPrice());
                holder.et_unit_price.setText(bean.getSingle_price());
                holder.tv_city.setText(bean.getName());
                holder.tv_city_ids.setText(bean.getSold_province());
                holder.iv_remove.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        data_json.remove(holder.getAdapterPosition());
                        notifyItemRemoved(holder.getAdapterPosition());
                    }
                });

                holder.tv_city.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        // 发送广播 刷新商品规格数据
                        intent.setAction("app.data.refresh");
                        ((Activity) mContext).sendBroadcast(intent);

                        intent.putExtra("index", index);
                        intent.putExtra("position", position);
                        intent.putExtra("tempId", bean.getSold_province());
                        intent.setClass(mContext, SaleAreaActivity.class);
                        ((Activity) mContext).startActivityForResult(intent, 200);

                    }
                });
            }

            @Override
            public int getItemCount() {
                return data_json.size();
            }

            public class ViewHolder extends RecyclerView.ViewHolder {
                ImageView iv_remove;
                TextView tv_city, tv_city_ids;
                EditText et_unit_price;
                TextView tv_price;

                public ViewHolder(View view) {
                    super(view);
                    iv_remove = (ImageView) view.findViewById(R.id.iv_remove);
                    tv_price = (TextView) view.findViewById(R.id.tv_price);
                    tv_city = (TextView) view.findViewById(R.id.tv_city);
                    et_unit_price = (EditText) view.findViewById(R.id.et_unit_price);
                    tv_city_ids = (TextView) view.findViewById(R.id.tv_city_ids);
                }
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    if (data != null) {
                        int index = data.getIntExtra("index", -1);
                        int position = data.getIntExtra("position", -1);
                        if (position != -1) {
                            String id = data.getStringExtra("id");
                            String name = data.getStringExtra("name");
                            GsonGb gsonGb = list.get(index);
                            beanList = gsonGb.getData_json();
                            GsonGb.Bean bean = beanList.get(position);
                            bean.setSold_province(id);
                            bean.setName(name);
                            adapter.clear();
                            adapter.addAll(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case 400:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
    }
}
